//
//  NetworkTools.swift
//  AFN-Swift
//
//  Created by 吴婷婷 on 15/11/7.
//  Copyright © 2015年 wutingting. All rights reserved.
//

import UIKit
import AFNetworking
///HTTP 请求方法枚举
enum KWRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
    
}

//MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {
    //应用程序信息
    private let appKey = "1330157804"
    private let appSecret = "14451314a5b199f81818dc4096b4c421"
    private let redirectUrl = "http://www.baidu.com"
    
    //网络请求回调
    typealias KWRequestCallBack = (result: AnyObject?, error: NSError?)->()
    
    //单例
    static let sharedTools: NetworkTools = {
        
        let tools = NetworkTools(baseURL: nil)
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
        
    }()
    
    ///Token字典模型
//    private var tokenDict: [String: AnyObject]? {
//        
//        if let token = UserAccountViewModel.sharedUserAccount.accessToken {
//            return ["access_token": token]
//        }
//        
//        return nil
//    }

}
//Mark: - 发布微博
extension NetworkTools {
    func sendStatus(status: String, image: UIImage? = nil, finished: KWRequestCallBack) {
        //1.获取参数
        var params = [String: AnyObject]()
        
        params["status"] = status
        
        if image == nil{
            //2.URL
            let urlString = "https://api.weibo.com/2/statuses/update.json"
            
            //3.发送请求
            tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
        } else {
            let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            let data = UIImagePNGRepresentation(image!)!
            
            upload(urlString, data: data, name: "pic", parameters: params, finished: finished)
        }
        
    }
}

//MARK: - 微博数据相关方法
extension NetworkTools {
    
    func loadStatus(since_id since_id: Int, max_id: Int, finished: KWRequestCallBack) {
        //1.获取参数
        var params = [String: AnyObject]()
        //判断是否有上拉或者下拉刷新数据
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {
            params["max_id"] = max_id
        }
        
        //2.URL
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //3.发送请求
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
        
        
    }
}
//MARK: - 用户信息相关方法
extension NetworkTools {
    
    func loadUserInfo(uid: String, finished: KWRequestCallBack){
        var params = [String: AnyObject]()

        let urlString = "https://api.weibo.com/2/users/show.json?"
        
        params["uid"] = uid
        
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: finished)
    }
}

//MARK: - OAuth相关方法
extension NetworkTools {
     ///OAuth授权URL
    /// - see: [http://open.weibo.com/wiki/Oauth2/authorize](http://open.weibo.com/wiki/Oauth2/authorize)
    var oauthURL: NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    ///加载accessToken
    func loadAccessToken(code: String, finished:KWRequestCallBack){
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let params = ["client_id":appKey,
            "client_secret":appSecret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirectUrl]
        
        request(.POST, URLString: urlString, parameters: params, finished: finished)
        
        
        //测试返回数据的类型
//        responseSerializer = AFHTTPResponseSerializer()
//        
//        POST(urlString, parameters: params, success: { (_, result) -> Void in
//            let json = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            print(json)
//            }, failure: nil)
        
    }
}



//MARK: - 封装AFN网络方法
extension NetworkTools {
    ///生成并检测token字典参数
    private func appendToken(inout parameters: [String: AnyObject]?)->Bool {
        guard let token = UserAccountViewModel.sharedUserAccount.accessToken else {
            return false
        }
        
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        parameters!["access_token"] = token
        
        return true
    }
    ///视同token进行网络请求
    private func tokenRequest(method: KWRequestMethod, URLString: String, var parameters: [String: AnyObject]?, finished:KWRequestCallBack) {
        //1.获取token字典
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "cn.karen.error", code: -101, userInfo: ["message": "token为空"]))
            
            return
        }
        //2.发起网络请求
        request(method, URLString: URLString, parameters: parameters, finished: finished)
    }
    
    ///网络请求方法
    private func request(method: KWRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished:KWRequestCallBack) {
        //定义成功回调
        let success = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            finished(result: result, error: nil)
        }
        //定义失败回调
        let error = { (task: NSURLSessionDataTask, error: NSError) -> Void in
            print(error)
            finished(result: nil, error: error)
        }
        
        
        if method == KWRequestMethod.GET {
            GET(URLString, parameters: parameters, success: success, failure: error)
        }else {
            POST(URLString, parameters: parameters, success: success, failure: error)
        }
    }
    ///上传文件
    private func upload(URLString: String, data: NSData, name: String , var parameters: [String: AnyObject]?, finished:KWRequestCallBack) {
        //判断是否能加载token
        if !appendToken(&parameters) {
            finished(result: nil, error: NSError(domain: "cn.karen.error", code: -101, userInfo: ["message": "token为空"]))
            
            return
        }
        
        POST(URLString, parameters: parameters,
            constructingBodyWithBlock: { (formdata) -> Void in
            formdata.appendPartWithFileData(data, name: name, fileName: "xxx", mimeType: "application/octet-stream")
            }, success: { (_, result) -> Void in
                finished(result: result, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
        
    }
}
